/*******************************************************************************
 * This file is part of blueprint4j www.blueprint4j.org.
 * 
 *     blueprint4j is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU Lesser General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * 
 *     blueprint4j is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU Lesser General Public License for more details.
 * 
 *     You should have received a copy of the GNU Lesser General Public License
 *     along with blueprint4j. If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/
package blueprint4j.gui.db;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Vector;

import javax.swing.AbstractButton;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;

import blueprint4j.Constants;
import blueprint4j.db.DBConnection;
import blueprint4j.db.DBTools;
import blueprint4j.db.DataException;
import blueprint4j.db.Entity;
import blueprint4j.db.FieldDate;
import blueprint4j.db.FieldDateTime;
import blueprint4j.db.FieldTime;
import blueprint4j.db.VectorEntity;
import blueprint4j.db.VectorField;
import blueprint4j.gui.AnimatingButton;
import blueprint4j.gui.Binder;
import blueprint4j.gui.BinderListner;
import blueprint4j.gui.Gui;
import blueprint4j.gui.TableSorter;
import blueprint4j.utils.BindException;
import blueprint4j.utils.Log;
import blueprint4j.utils.Settings;
import blueprint4j.utils.VectorString;


public class EntityPanel extends JPanel
		implements
			ListSelectionListener,
			ActionListener,
			BinderListner {
	private static final long serialVersionUID = 1L;
	private Entity entity;
	private Entity selected_entity = null;
	private DBConnection connection;
	private int max_items; // Max number of entries normally shown
	private int max_items_offset = 1; // The next Max number of items to be
										// shown
	private EntityPanelFieldBinder[] binders = null; // This must be set
	private Vector<String> column_names = null;
	private VectorEntity entites_list = null;
	private VectorEntityPanelSelectionListner listners = new VectorEntityPanelSelectionListner();
	private VectorEntityPanelNewEventListner add_events = new VectorEntityPanelNewEventListner();
	private JTable table = null;
	private JScrollPane scroll = new JScrollPane();
	private JButton new_button;
	private JButton delete_button;
	private JButton search_button;
	private JButton refresh_button;
	private JButton import_button;
	private JButton export_button;
	private JButton prev_button;
	private JButton next_button;

	private EntityPanelDeleteAuthorizer authorizer = new EntityPanelDeleteAuthorizerDefault();
	private HashMap<JComponent,Boolean> map = new HashMap<JComponent,Boolean>();
	private Vector<Vector<JComponent>> data = new Vector<Vector<JComponent>>();
	private int selection_index;
	private DefaultTableModel model;
	private String other_where = null, complete_where = null;
	// private String original_other_where= null,original_complete_where= null;
	private boolean select_first = false, select_lastselect = true;
	private JButton extra_buttons[] = null;
	private EntityPanelSelectionListner extra_listeners[] = null;
	private EntityEditor entity_editor = null;

	// private Integer total_column_width = null;

	private EntityWizard entity_wizard = null;

	public EntityPanel(Entity p_entity, EntityPanelFieldBinder[] p_binders)
			throws SQLException, DataException, BindException {
		this(p_entity, p_binders, Settings.getInt(
				"gui.entity_panel.default_max_items", 200));
	}

	public EntityPanel(Entity p_entity, EntityPanelFieldBinder[] p_binders,
			int max) throws SQLException, DataException, BindException {
		this(p_entity, p_binders, max, null, null);
	}

	public EntityPanel(Entity p_entity, EntityPanelFieldBinder[] p_binders,
			int max, JButton p_extra_buttons[],
			EntityPanelSelectionListner p_extra_listeners[],
			String p_other_where) throws SQLException, DataException,
			BindException {
		super(new BorderLayout());
		Gui.addEnter4FocusShift(this);
		entity = p_entity;
		binders = p_binders;
		connection = entity.getConnection();
		other_where = p_other_where;
		// original_other_where= p_other_where;
		setMaxItemsShow(max);
		setPreferredSize(new Dimension(270, 300));
		extra_buttons = p_extra_buttons;
		extra_listeners = p_extra_listeners;
		for (int i = 0; extra_buttons != null && i < extra_buttons.length; i++) {
			formatButton(extra_buttons[i]);
			extra_buttons[i].addActionListener(this);
		}
		
	    //Dags - put this in so that the first item in the entity list for each entity panel will be selected
		setSelectFirst(true);
		setSelectLastSelect(false);
		setSelectedEntity(p_entity); 
        //Dags
        
		build();

		// BY DEFAULT IMPORTS ARE DISABLED
		enableImport(false);
	}

	public EntityPanel(Entity p_entity, EntityPanelFieldBinder[] p_binders,
			int max, JButton p_extra_buttons[],
			EntityPanelSelectionListner p_extra_listeners[])
			throws SQLException, DataException, BindException {
		this(p_entity, p_binders, max, p_extra_buttons, p_extra_listeners, null);
	}

	/**
	 * If the entity wizard is set then if the new entity button is clicked, the
	 * wizard will appear
	 */
	public void setEntityWizard(EntityWizard entity_wizard) {
		this.entity_wizard = entity_wizard;
	}

	public int getCurrentSize() {
		return entites_list.size();
	}

	/*
	 * Set the column total width This will make the last column the total width -
	 * all other columns
	 * 
	 * public void setColumnTotalWidth(int width){
	 * System.out.println("setColumnTotalWidth " + width); Double adjust_width =
	 * null; this.total_column_width = new Integer(width); int total_width = 0;
	 * for (int t = 0;t < binders.length;t++) { total_width +=
	 * binders[t].getColumnWidth(); } adjust_width = new Double(width /
	 * (total_width*1.0));
	 * 
	 * for (int t = 0;t < binders.length;t++) { TableColumn c =
	 * table.getColumn(binders[t].getColumnName());
	 * c.setPreferredWidth((int)Math.round(binders[t].getColumnWidth()*adjust_width.doubleValue())); } }
	 */

	public EntityPanel(Entity p_entity, EntityPanelFieldBinder[] p_binders,
			JButton p_extra_buttons[],
			EntityPanelSelectionListner p_extra_listeners[])
			throws SQLException, DataException, BindException {
		this(p_entity, p_binders, Settings.getInt(
				"gui.entity_panel.default_max_items", 200), p_extra_buttons,
				p_extra_listeners);
	}

	public void setEntityEditor(EntityEditor entity_editor) {
		this.entity_editor = entity_editor;
	}

	public void setSelectFirst(boolean select_first) {
		this.select_first = select_first;
	}

	public void setSelectLastSelect(boolean select_lastselect) {
		this.select_lastselect = select_lastselect;
	}

	public void deselectEntity() {
		selected_entity = null;
		actionRefresh();
	}

	public Entity getSelectedEntity() {
		return selected_entity;
	}
	
	//Dags added this
	public void setSelectedEntity(Entity entity) {
		selected_entity = entity;
	}

	public void addSelectionListner(EntityPanelSelectionListner listner) {
		listners.add(listner);
		listner.selection(selected_entity);
	}

	public void removeSelectionListner(EntityPanelSelectionListner listner) {
		listners.remove(listner);
	}

	public void addNewEventListner(EntityPanelNewEventListner listner) {
		add_events.add(listner);
	}

	public void removeNewEventListner(EntityPanelNewEventListner listner) {
		add_events.remove(listner);
	}

	public void enableAdd(boolean enable) {
		new_button.setVisible(enable);
	}

	public void enableSearch(boolean enable) {
		search_button.setVisible(enable);
	}

	public void enableRefresh(boolean enable) {
		refresh_button.setVisible(enable);
	}

	public void enableDelete(boolean enable) {
		delete_button.setVisible(enable);
	}

	public void enableImport(boolean enable) {
		import_button.setVisible(enable);
	}

	public void enableExport(boolean enable) {
		export_button.setVisible(enable);
	}

	public void enablePrev(boolean enable) {
		prev_button.setVisible(enable);
	}

	public void enableNext(boolean enable) {
		next_button.setVisible(enable);
	}

	private void build() throws SQLException, DataException, BindException {
		// Create buttons
		try {
			new_button = new AnimatingButton("New",
					new String[]{Constants.ICON_BASE+"actions/edit_add.png"}, 1);
			new_button.setToolTipText("Create a new entity");
			delete_button = new AnimatingButton("Delete",
					new String[]{Constants.ICON_BASE+"actions/cnrdelete-all.png"}, 1);
			delete_button.setToolTipText("Delete current entity");
			search_button = new AnimatingButton("Search",
					new String[]{Constants.ICON_BASE+"actions/search.png"}, 1);
			search_button.setToolTipText("Search through list");
			refresh_button = new AnimatingButton("Refresh",
					new String[]{Constants.ICON_BASE+"actions/agt_reload.png"}, 1);
			import_button = new AnimatingButton("Import",
					new String[]{Constants.ICON_BASE+"actions/db_update.png"}, 1);
			export_button = new AnimatingButton("Export",
					new String[]{Constants.ICON_BASE+"actions/db_comit.png"}, 1);
			prev_button = new AnimatingButton("Prev",
					new String[]{Constants.ICON_BASE+"actions/1leftarrow.png"}, 1);
			next_button = new AnimatingButton("Next",
					new String[]{Constants.ICON_BASE+"actions/1rightarrow.png"}, 1);
			refresh_button.setToolTipText("Refresh current entity");
		} catch (IOException ioe) {
			Log.debug.out(ioe);
		}

		// Add buttons to display
		formatButton(new_button);
		formatButton(delete_button);
		formatButton(search_button);
		formatButton(refresh_button);
		formatButton(import_button);
		formatButton(export_button);
		formatButton(prev_button);
		formatButton(next_button);
		JPanel all_buttons = new JPanel(new BorderLayout());
		Box buttons = Box.createHorizontalBox();
		buttons.add(new_button);
		buttons.add(refresh_button);
		buttons.add(search_button);
		buttons.add(import_button);
		buttons.add(export_button);
		buttons.add(prev_button);
		buttons.add(next_button);
		// Box extra_bts = Box.createHorizontalBox();
		for (int i = 0; extra_buttons != null && i < extra_buttons.length; i++) {
			buttons.add(extra_buttons[i]);
		}
		all_buttons.add(buttons, BorderLayout.CENTER);
		all_buttons.add(delete_button, BorderLayout.EAST);
		add(all_buttons, BorderLayout.NORTH);

		// Add scroll pane
		add(scroll, BorderLayout.CENTER);
		scroll
				.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

		// Create table details
		column_names = new Vector<String>();
		for (int t = 0; t < binders.length; t++) {
			column_names.add(binders[t].getColumnName());
		}
		buildListFromString(null);
	}

	private void formatButton(JButton button) {
		button.setHorizontalAlignment(AbstractButton.CENTER);
		button.setHorizontalTextPosition(AbstractButton.CENTER);
		button.setVerticalTextPosition(AbstractButton.BOTTOM);
		button.setIconTextGap(0);
		button.setMargin(new Insets(0, 0, 0, 0));
		button.setFocusable(false);
		button.addActionListener(this);
		if (Settings.getBoolean("gui.entity_panel.hide_button_text", true)) {
			button.setText(null);
		}
	}

	public void setMaxItemsShow(int max) {
		max_items = max;
	}

	public String getOtherWhere() {
		return other_where;
	}

	public void setOtherWhere(String p_other_where) throws SQLException,
			DataException, BindException {
		other_where = p_other_where;
		buildListFromString(null);
	}

	public void setCompleteWhere(String complete_where) throws BindException {
		try {
			this.complete_where = complete_where;
			/*
			 * other_where = null; if (original_complete_where == null){
			 * original_complete_where = complete_where; }
			 */
			buildListFromString(null);
		} catch (Exception exception) {
			other_where = null;
			throw new BindException(exception);
		}
	}

	private void buildListFromString(String search) throws SQLException,
			DataException, BindException {
		Entity tmp_selected_entity = selected_entity;
		Entity first = null;
		Entity item = null;
		if (search != null && search.trim().length() == 0) {
			search = null;
		}

		if (search != null) {
			if (entity.shouldSort()) {
				item = entity.findByOrder(entity
						.buildSearchForAnyColumn(search));
			} else {
				item = entity.findOrderByNameFields(entity
						.buildSearchForAnyColumn(search));
			}
		} else {
			if (complete_where != null) {
				search = complete_where;
			} else if (other_where != null) {
				search = other_where;
			} else {
				search = "1=1";
			}
			if (search.indexOf("where") == -1) {
				search = "select * from " + entity.getTableName() + " where "
						+ search;
			}
			item = entity.rebuildFromResultSet(entity.getConnection()
					.createStatement().executeQuery(search));
		}
		entites_list = new VectorEntity();
		int cnt = 0;
		for (; item != null && cnt++ < max_items * max_items_offset; item = item
				.getNextEntity()) {
			if (cnt >= (max_items * (max_items_offset - 1))) {
				if (first == null && select_first) {
					first = item;
				}
				entites_list.add(item);
			}
		}
		if (entites_list.size() < max_items) {
			next_button.setEnabled(false);
		} else {
			next_button.setEnabled(true);
		}
		if (max_items_offset == 1) {
			prev_button.setEnabled(false);
		} else {
			prev_button.setEnabled(true);
		}
		if (entites_list.size() > 0) {
			entites_list.get(0).closeResultSet();
		}
		buildFromItem();
		model = new DefaultTableModel(data, column_names) {
			private static final long serialVersionUID = 1L;

			public boolean isCellEditable(int row, int column) {
				return false;
			}
		};
		TableSorter sorter = new TableSorter(model);
		table = new JTable(sorter);
		sorter.setTableHeader(table.getTableHeader());
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		table.setShowVerticalLines(false);
		table.setShowHorizontalLines(false);
		table.setFocusable(true);
		table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
		table.getSelectionModel().addListSelectionListener(this);
		table.setIntercellSpacing(new Dimension(0, 0));
		table.setDefaultRenderer(Object.class, new TableCellRenderer() {
			public Component getTableCellRendererComponent(JTable table,
					Object value, boolean isSelected, boolean hasFocus,
					int row, int column) {
				JComponent component = (JComponent) value;
				if (map.get(component) != null) {
					component.setOpaque(map.get(component));
				} else {
					map.put(component, component.isOpaque());
				}
				if (!component.isOpaque()) {
					component.setOpaque(true);
					if (isSelected) {
						
						component.setForeground(Gui.getRowSelectedColorForground());
						component.setBackground(Gui.getRowSelectedColor());
					} else if (((row / 3) & 1) == 1) {
						component.setForeground(Gui.getRowNormalColorForground());
						component.setBackground(Gui.getRowHighlighterColor());
					} else {
						component.setForeground(Gui.getRowNormalColorForground());
						component.setBackground(Gui.getRowNormalColor());
					}
				}
				return component;
			}
		});
		// if (total_column_width != null) {
		// setColumnTotalWidth(total_column_width.intValue());
		// } else {
		for (int t = 0; t < binders.length; t++) {
			TableColumn c = table.getColumn(binders[t].getColumnName());
			c.setPreferredWidth(binders[t].getColumnWidth());
		}
		// }
		scroll.setViewportView(table);
		table.setDragEnabled(true);
		// Mark selection
		if (select_lastselect && entites_list != null
				&& tmp_selected_entity != null
				&& entites_list.indexOf(tmp_selected_entity) > -1) {
			table.setRowSelectionInterval(entites_list
					.indexOf(tmp_selected_entity), entites_list
					.indexOf(tmp_selected_entity));
		} else {
			if (first != null) {
				table.setRowSelectionInterval(0, 0);
			}
			// Remove selection
			selected_entity = first;
//			if (selected_entity != null) {
//				setEntityPanel(selected_entity.getFieldAction(),this);
//			}
			listners.selection(first);
		}
	}
	
//    public void setEntityPanel(VectorFieldAction va,EntityPanel entity_panel) {
//        for (int i =0;i <va.size();i++) {
//            va.get(i).setEntityPanel(entity_panel);
//        }
//    }


	private void buildFromItem() throws DataException, SQLException {
		data.clear();
		for (int t = 0; t < entites_list.size(); t++) {
			Entity item = entites_list.get(t);
			Vector<JComponent> row = new Vector<JComponent>();
			for (int y = 0; y < binders.length; y++) {
				row.add(binders[y].getFieldComponent(item));
			}
			data.add(row);
		}
	}

	public void valueChanged(ListSelectionEvent e) {
		try {
			if (e.getValueIsAdjusting() == false) {
				if (entity_editor != null) {
					if (!entity_editor.save()) {
						return;
					}
				}
				selection_index = table.getSelectionModel()
						.getLeadSelectionIndex();
				// THIS CAN HAPPEN WHEN YOU DELETE AN ENTITY
				if (entites_list.size() > 0
						&& entites_list.size() > selection_index) {
					if (selection_index == -1) {
						selected_entity = entites_list.get(0);
					} else {
						selected_entity = entites_list.get(selection_index);
					}
					if (selected_entity.isLoaded()) {
						selected_entity.reload();
					}
					listners.selection(selected_entity);
				}
			}
		} catch (Exception exception) {
			Log.debug.out(exception);
		}
	}

	public void addNotify() {
		super.addNotify();
		listners.selection(selected_entity);
	}

	public void removeNotify() {
		super.removeNotify();
		listners.selection(null);
	}

	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == new_button) {
			actionNew();
		}
		if (e.getSource() == search_button) {
			actionSearch();
		}
		if (e.getSource() == delete_button) {
			actionDelete();
		}
		if (e.getSource() == refresh_button) {
			actionRefresh();
		}
		if (e.getSource() == import_button) {
			actionImport();
		}
		if (e.getSource() == export_button) {
			actionExport();
		}
		if (e.getSource() == prev_button) {
			actionPrev();
		}
		if (e.getSource() == next_button) {
			actionNext();
		}
		for (int i = 0; extra_buttons != null && i < extra_buttons.length; i++) {
			if (extra_listeners != null && e.getSource() == extra_buttons[i]
					&& extra_listeners[i] != null) {
				extra_listeners[i].selection(selected_entity);
			}
		}
	}

	public void actionNew() {
		try {
			Entity new_entity = entity.createNew();
			if (entity_wizard != null) {
				new_entity = entity_wizard.show(new_entity);
			}
			if (new_entity != null) {
				Vector<JComponent> row = new Vector<JComponent>();
				if (add_events.eventNew(new_entity)) {
					entites_list.add(new_entity);
					for (int y = 0; y < binders.length; y++) {
						row.add(binders[y].getFieldComponent(new_entity));
					}
					model.addRow(row);
					table.getSelectionModel().setSelectionInterval(
							model.getRowCount() - 1, model.getRowCount() - 1);
				}
			}
			
		} catch (SQLException sqle) {
			sqle.printStackTrace();
			Log.debug.out(sqle);
		}
	}

	public void actionUp() {
		if (table.getSelectedRow() > 0) {
			for (int col = 0; col < table.getColumnCount(); col++) {
				Object value = model.getValueAt(table.getSelectedRow(), table
						.getSelectedColumn());
				model.setValueAt(model.getValueAt(table.getSelectedRow() - 1,
						col), table.getSelectedRow(), col);
				model.setValueAt(value, table.getSelectedRow() - 1, col);
				Entity entity = entites_list.get(table.getSelectedRow());
				entites_list.set(table.getSelectedRow(), entites_list.get(table
						.getSelectedRow() - 1));
				entites_list.set(table.getSelectedRow() - 1, entity);
			}
		}
	}

	public void actionRefresh() {
		try {
			if (entity_editor != null) {
				if (entity_editor.save()) {
					buildListFromString(null);
				}
			} else {
				buildListFromString(null);
			}
		} catch (Exception sqle) {
			JOptionPane.showMessageDialog(null, sqle.getMessage());
			Log.debug.out(sqle);
		}
	}

	public void actionSearch() {
		try {
			max_items_offset = 1;
			buildListFromString(JOptionPane.showInputDialog(null,
					"Enter a search value"));
		} catch (Exception exception) {
			Log.debug.out(exception);
		}
	}

	private static class ImportExportDialog extends JDialog
			implements
				ActionListener {
		private static final long serialVersionUID = 1L;
		private JButton process = null;
		private JTextField datetimeformat = new JTextField(
				"yyyy MM dd HH:mm:ss");
		private JComboBox process_type = new JComboBox(new Object[]{"CSV"});
		private JComboBox process_sync = null;
		private JFileChooser file_chooser = new JFileChooser();
		private JCheckBox check[] = null;
		private Entity entity = null;
		private VectorEntity entites_list = null;
		private VectorField vfield = null;
		private boolean export;

		public ImportExportDialog(Entity entity, VectorEntity entites_list,
				VectorField vfield, boolean export) {
			super();
			this.entites_list = entites_list;
			setModal(true);
			this.entity = entity;
			this.vfield = vfield;
			this.export = export;
			process = new JButton(export ? "Export" : "Import");
			process.addActionListener(this);
			VectorString names = vfield.getNames();
			names.add(0, "Do Not Sync");
			process_sync = new JComboBox(names.toArray());
			check = new JCheckBox[vfield.size()];
			JPanel main = new JPanel();
			JPanel south = new JPanel();
			getContentPane().setLayout(new BorderLayout());
			south.setLayout(new BorderLayout());
			main.setLayout(new GridLayout((int) Math.round(Math
					.sqrt(check.length)) * 2, (int) Math.round(Math
					.sqrt(check.length) / 1.5)));
			for (int i = 0; i < vfield.size(); i++) {
				check[i] = new JCheckBox(vfield.get(i).getName());
				check[i].setSelected(true);
				check[i].setEnabled(export || !vfield.get(i).isKey());
				main.add(check[i]);
			}
			getContentPane().add(process, BorderLayout.NORTH);
			getContentPane().add(main, BorderLayout.CENTER);

			south.add(datetimeformat, BorderLayout.WEST);
			south.add(process_type, BorderLayout.CENTER);
			if (!export) {
				south.add(process_sync, BorderLayout.EAST);
			}
			getContentPane().add(south, BorderLayout.SOUTH);
			pack();
			setLocationRelativeTo(null);
		}

		public void actionPerformed(ActionEvent event) {
			try {
				if (file_chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
					VectorField vf = new VectorField();
					for (int i = 0; i < vfield.size(); i++) {
						if (check[i].isSelected()) {
							vf.add(vfield.get(i));
						}
					}
					if (export) {
						FileOutputStream stream = new FileOutputStream(
								file_chooser.getSelectedFile());
						for (int i = 0; i < entites_list.size(); i++) {
							stream.write((entites_list.get(i).getFields()
									.getFiltered(vf).getSerializable()
									.toString(",") + "\r\n").getBytes());
						}
						stream.close();
					} else {
						SimpleDateFormat dtformat = new SimpleDateFormat(
								datetimeformat.getText());
						SimpleDateFormat dformat = null;
						SimpleDateFormat tformat = null;
						int index = 0;
						index = datetimeformat.getText().indexOf("H");
						if (index == -1) {
							index = datetimeformat.getText().indexOf("h");
						}
						if (index == -1) {
							index = datetimeformat.getText().indexOf("K");
						}
						if (index == -1) {
							index = datetimeformat.getText().indexOf("k");
						}
						dformat = new SimpleDateFormat(datetimeformat.getText()
								.substring(0, index));
						tformat = new SimpleDateFormat(datetimeformat.getText()
								.substring(index + 1));
						// IMPORT THIS NEEDS TO HAPPEN IN A TRANSCATION
						DBConnection dbcon = DBTools.getNDC();
						try {
							LineNumberReader reader = new LineNumberReader(
									new InputStreamReader(new FileInputStream(
											file_chooser.getSelectedFile())));
							for (String line = reader.readLine(); line != null; line = reader
									.readLine()) {
								VectorString items = new VectorString(line, ",");
								if (items.size() != vf.size()) {
									throw new DataException(
											"Imported field count does not match specified");
								}
								// CONVERT DATE AND TIME'S INTO CORRECT FORMAT
								for (int i = 0; i < vf.size(); i++) {
									if (items.get(i) != null
											&& !"null".equals(items.get(i))) {
										if (vf.get(i) instanceof FieldTime) {
											items.set(i, FieldTime.time_format
													.format(tformat.parse(items
															.get(i))));
										} else if (vf.get(i) instanceof FieldDate) {
											items.set(i, FieldDate.date_format
													.format(dformat.parse(items
															.get(i))));
										} else if (vf.get(i) instanceof FieldDateTime) {
											items
													.set(
															i,
															FieldDateTime.date_format
																	.format(dtformat
																			.parse(items
																					.get(i))));
										}
									}
								}
								Entity entityinst = null;
								if (!process_sync.getSelectedItem().equals(
										"Do Not Sync")) {
									entityinst = entity
											.find(process_sync
													.getSelectedItem()
													+ " = '"
													+ items
															.get(vf
																	.indexOf(""
																			+ process_sync
																					.getSelectedItem()))
													+ "'");
								}
								if (entityinst == null) {
									entityinst = entity.getNewInstance();
								}
								entityinst.setNewConnection(dbcon);
								entityinst.getFields().getFiltered(vf)
										.setSerializable(items);
								entityinst.save();
							}
							reader.close();
							dbcon.commit();
						} catch (Exception exception) {
							dbcon.rollback();
							throw exception;
						} finally {
							dbcon.close();
						}
					}
					JOptionPane.showMessageDialog(null,
							"All entities sucessfully processed");
					dispose();
				}
			} catch (Exception exception) {
				Log.debug.out(exception);
				JOptionPane.showMessageDialog(null, exception.getMessage());
			}
		}
	}

	public void actionExport() {
		try {
			if (entites_list.size() > 0) {
				new ImportExportDialog(entity, entites_list, entity.getFields()
						.getFiltered(-1, true), true).setVisible(true);
			} else {
				JOptionPane.showMessageDialog(null, "No entities to export");
			}
		} catch (Exception exception) {
			Log.debug.out(exception);
		}
	}

	public void actionImport() {
		new ImportExportDialog(entity, entites_list, entity.getFields()
				.getFiltered(-1, true), false).setVisible(true);
		actionRefresh();
	}

	public void actionPrev() {
		max_items_offset--;
		actionRefresh();
	}

	public void actionNext() {
		max_items_offset++;
		actionRefresh();
	}

	public void actionDelete() {
		if (selected_entity != null
				&& (authorizer == null || authorizer.canDelete(selected_entity))) {
			try {
				// Remove from list
				entites_list.remove(selection_index);
				entity_editor.getBinder().removeBindable(selected_entity);
				// Delete the entity
				selected_entity.delete();
				connection.commit();
				model.removeRow(selection_index);
				selected_entity = null;
				listners.selection(null);
				// actionRefresh();
			} catch (BindException be) {
				JOptionPane.showMessageDialog(null, be.getMessage());
				Log.debug.out(be);
			} catch (SQLException sqle) {
				JOptionPane.showMessageDialog(null, sqle.getMessage());
				Log.debug.out(sqle);
			}
		}
	}

	public EntityPanelDeleteAuthorizer getAuthorizer() {
		return authorizer;
	}

	public void setAuthorizer(EntityPanelDeleteAuthorizer p_authorizer) {
		authorizer = p_authorizer;
	}

	public void saved(Binder binder) {
		try {
			buildFromItem();
			table.repaint();
		} catch (DataException de) {
			de.printStackTrace();
			Log.critical.out(de);
			System.exit(-1);
		} catch (SQLException sqle) {
			sqle.printStackTrace();
			Log.critical.out(sqle);
			System.exit(-1);
		}
	}

	public void restore(Binder binder) {
	}

	public void reload(Binder binder) {
	}

	public void intoBindings(Binder binder) {
	}

}
